package com.redeemer150.aisuperagent.tools;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 炼金术士
 * @version 1.0
 * @description: TODO
 * @date 2025/7/22 09:16
 */
@Deprecated
public class BaiduWebSearchTool {
    // SearchAPI 的搜索接口地址
    private static final String SEARCH_API_URL = "https://www.searchapi.io/api/v1/search";

    private  final  String apiKey;

    public BaiduWebSearchTool(String apiKey) {
        this.apiKey=apiKey;
    }

    @Tool(description = "Search for information on the web")
    public String searchWeb(@ToolParam(description = "Search query keyword")  String query) {
        Map<String,Object> paramMap = Map.of("q",query,"apiKey",apiKey,"engine","baidu");
        try {
            String response = HttpUtil.get(SEARCH_API_URL, paramMap);
            //取前5条数据
            JSONObject jsonObject = JSONUtil.parseObj(response);
            // 提取 organic_results 部分
            JSONArray organicResults = jsonObject.getJSONArray("organic_results");
            List<Object> objects = organicResults.subList(0, 5);
            // 拼接搜索结果为字符串
            String result = objects.stream().map(obj -> {
                JSONObject tmpJSONObject = (JSONObject) obj;
                return tmpJSONObject.toString();
            }).collect(Collectors.joining(","));
            return result;
        }catch (Exception e){
            return "Error searching Baidu: " + e.getMessage();
        }
    }
}
